//
//  WBComposeTypeView.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/23.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit
import pop

// 撰写微博类型视图
class WBComposeTypeView: UIView {
    
    let buttonInfo = [
        ["imageName":"tabbar_compose_idea", "title":"文字", "className":"WBComposeController"],
        ["imageName":"tabbar_compose_photo", "title":"照片/视频"],
        ["imageName":"tabbar_compose_weibo", "title":"长微博"],
        ["imageName":"tabbar_compose_lbs", "title":"签到"],
        ["imageName":"tabbar_compose_review", "title":"点评"],
        ["imageName":"tabbar_compose_more", "title":"更多", "actionName":"showMore"],
        ["imageName":"tabbar_compose_friend", "title":"好友圈"],
        ["imageName":"tabbar_compose_wbcamera", "title":"微博相机"],
        ["imageName":"tabbar_compose_music", "title":"音乐"],
        ["imageName":"tabbar_compose_shooting", "title":"拍摄"]
    ]
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var closeBtnCenterxCons: NSLayoutConstraint!
    @IBOutlet weak var returnBtnCenterxCons: NSLayoutConstraint!
    @IBOutlet weak var returnBtn: UIButton!
    
    var completionBlock: ((_ className: String?)->())?
    
    class func composeTypeView() -> WBComposeTypeView {
        let nib = UINib.init(nibName: "WBComposeTypeView", bundle: nil)
        
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! WBComposeTypeView
        view.frame = UIScreen.main.bounds
        
        view.setupUI()
        
        return view
    }
    
    func show(completion: @escaping (_ className: String?)->()) {
        
        completionBlock = completion
        
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {return}
        
        vc.view.addSubview(self)
        
        showCurrentView()
        showButtons()
    }
}

// MARK: - 按钮点击方法
private extension WBComposeTypeView {
    /// 从scrollView的第二页返回到第一页
    @IBAction func back() {
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        
        let margin = IPHONE_WIDTH / 4
        
        closeBtnCenterxCons.constant -= margin
        returnBtnCenterxCons.constant += margin
        
        UIView.animate(withDuration: 0.25, animations: {
            self.layoutIfNeeded()
        }) { _ in
            self.returnBtn.isHidden = true
        }
    }
    
    /// 关闭当前视图
    @IBAction func close() {
        hideButtons()
    }
    
    /// 展示scrollView第二页
    @objc func showMore() {
        scrollView.setContentOffset(CGPoint(x: IPHONE_WIDTH, y: 0), animated: true)
        returnBtn.isHidden = false
        
        let margin = IPHONE_WIDTH / 4
        
        closeBtnCenterxCons.constant += margin
        returnBtnCenterxCons.constant -= margin
        
        UIView.animate(withDuration: 0.25, animations: {
            self.layoutIfNeeded()
        })
    }
    
    /// 点击按钮的监听
    ///
    /// - parameter sender: 点击的那个按钮
    @objc func clickMore(sender: WBComposeTypeButton) {
        
        debugPrint("-----------点我-------------")
        
        let page = Int(scrollView.contentOffset.x / IPHONE_WIDTH)
        let view = scrollView.subviews[page]
        
        for btn in view.subviews {
            let animScale: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let animAlpha: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            let scale = (btn == sender) ? 2 : 0.2
            
            animScale.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            animScale.duration = 0.5
            
            animAlpha.toValue = 0.2
            animAlpha.duration = 0.5
            
            btn.pop_add(animScale, forKey: nil)
            pop_add(animAlpha, forKey: nil)
            
            animAlpha.completionBlock = { _, _ in
                self.completionBlock?(sender.className)
            }
        }
    }
}

//MARK: - 动画相关
private extension WBComposeTypeView {
    /// 显示当前视图
    func showCurrentView() {
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 0
        anim.toValue = 1
        
        pop_add(anim, forKey: nil)
    }
    
    /// 显示撰写按钮
    func showButtons() {
        let v = scrollView.subviews[0]
        
        for (i, btn) in v.subviews.enumerated() {
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y + IPHONE_HEIGHT
            anim.toValue = btn.center.y
            anim.springBounciness = 10
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            btn.layer.pop_add(anim, forKey: nil)
        }
    }
    
    /// 隐藏撰写的按钮
    func hideButtons() {
        let page = Int(scrollView.contentOffset.x / IPHONE_WIDTH)
        
        // 获取当前显示的子视图
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated() {
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + IPHONE_HEIGHT
            
            // 隐藏动画的顺序是从最后一个开始，和显示的顺序相反
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            
            btn.layer.pop_add(anim, forKey: nil)
            
            // 最后一个动画执行完毕，进行回调，进行整个视图的隐藏
            if i == 0 {
                anim.completionBlock = { _, _ in
                    self.hideCurrentView()
                }
            }
        }
    }
    
    /// 隐藏当前视图
    func hideCurrentView() {
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)
        
        anim.completionBlock = { _, _ in
            self.removeFromSuperview()
        }
    }
}

//MARK: - UI相关
private extension WBComposeTypeView {
    func setupUI() {
        // 不调用该方法，无法取到scrollView准确的bounds
        layoutIfNeeded()
        
        for i in 0..<2 {
            // 创建类型按钮
            let v = UIView()
            
            v.frame = scrollView.bounds.offsetBy(dx: CGFloat(i) * IPHONE_WIDTH, dy: 0)
            
            addButton(v: v, index: i * 6)
            
            scrollView.addSubview(v)
        }
        
        scrollView.contentSize = CGSize(width: IPHONE_WIDTH * 2, height: 0)
    }
    
    func addButton(v: UIView, index: Int) {
        // 从index开始添加六个按钮
        let count = 6
        
        for i in index..<(index + count) {
            
            if i >= buttonInfo.count {break}
            
            // 从数组中获取名称和图片
            guard let imageName = buttonInfo[i]["imageName"],
                let title = buttonInfo[i]["title"] else {continue}
            
            let btn = WBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            
            if let actionName = buttonInfo[i]["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }else{
                btn.addTarget(self, action: #selector(clickMore), for: .touchUpInside)
            }
            
            btn.className = buttonInfo[i]["className"]
            
            // 添加到视图
            v.addSubview(btn)
        }
        
        for (i, btn) in v.subviews.enumerated() {
            
            /// 同一行的按钮的间距
            let intervalX = (IPHONE_WIDTH - 300) / 4
            
            let intervalY: CGFloat = 24
            
            let width = btn.bounds.width
            let height = btn.bounds.height
            
            btn.frame = btn.bounds.offsetBy(dx: CGFloat(i % 3) * width + CGFloat(i % 3 + 1) * intervalX, dy: CGFloat(i / 3) * (height + intervalY))
        }
    }
}
